package cn.caplike.demo.repository.java;

import org.apache.commons.io.FileUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * Description: 从网络中读取文件
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-10-13 18:13
 */
public class ReadFileFromUrl {

    public static void main(String[] args) throws Exception {
        final URL url = new URL("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2393599674,1372306077&fm=15&gp=0.jpg"/*"http://test.charmplus.cn/file/20201013/9c52d69aa10c449f9b59dc145b07cbfc.p12"*/);
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(3000);

        try (
                final InputStream inputStream = connection.getInputStream();
                final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
        ) {
            final byte[] buffer = new byte[1024];
            int len;

            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            final byte[] bytes = outputStream.toByteArray();
            final String encoded = new String(Base64.getEncoder().encode(bytes));
            System.out.println(encoded);

            // ~ 解析 base64 编码后的图片字节
            // ---------------------------------------------------------------------------------------------------------

            final File file = new File(FileUtils.getTempDirectoryPath() + "cachedFileName");
            try (
                    final FileOutputStream out = new FileOutputStream(file);
                    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out)
            ) {
                bufferedOutputStream.write(Base64.getDecoder().decode(encoded));
            }
            System.out.println(file.getAbsolutePath());
        }
    }

}
